// import {getImageBySrc} from './mcommon.js';
class Game {
  constructor() {
    let g = {
      // 11
      // 设置游戏状态
      state: 0,
      // 登录
      state_LOADING: 0,
      // 开始
      state_START: 1,
      // 游戏开始运行
      state_RUNNING: 2,
      // 暂停游戏
      state_STOP: 3,
      // 游戏结束，玩家胜利
      state_PLANTWON: 4,
      // 游戏结束，僵尸胜利
      state_ZOMBIEWON: 5,
      //设置动画频数
      fps: window.main.fps,
      //是否绘制植物
      ifPlant: false,
      //鼠标x坐标
      mouseX: 0,
      //鼠标y坐标    
      mouseY: 0,
      mouseMovex: 0,
      mouseMovey: 0,
      //鼠标移动可种植区域的行坐标                                                  
      mouseRow: 0,
      //鼠标移动可种植区域的列坐标                                            
      mouseCol: 0,
      //定义是否可点击图片，和card中的clickcard相联系
      clickcardg: false,
      //鼠标点击图片获得卡片对象
      card: null,
      //创建铲子对象
      shovel: null,
      //更新游戏进程图片
      step: 1,
      //判断游戏是否开始
      isbegin: false,
      //最后一秒频数
      lastUpdateTime: 0,
      //判断是否更新最后一频时间
      ishasCollided: false,
    };
    Object.assign(this, g);
  }

  // 创建，并初始化当前对象
  static new() {
    let g = new this();
    g.init();
    return g;
  }

  drawsunBg() {
    // 确保 context 存在
    let img = getImageBySrc(allImgSrcObj.sunbg)
    context.drawImage(img, 0, 0, 500, 80)

  }

  drawReturn() {
    let img = getImageBySrc(allImgSrcObj.exit1)
    context.drawImage(img, 900, 0, 100, 80)
  }


  drawTextSun() {
    let sunSum = new sunNum()
    sunSum.draw(context)
  }

  drawCards() {
    let cards = window.main.cards
    for (let card of cards) {
      card.draw(context)
    }
  }

  //创建铲子对象
  drawShovelbg() {
    let shovel = Shovel.new()
    shovel.draw(context)
  }

  drawCars() {
    let cars = window.main.cars
    for (let car of cars) {
      car.update()
      car.draw(context)
    }
    // console.log(cars)
  }


  drawStepImg() {
    let g = this
    let stepImage = null;
    if (g.step === 1) {
      stepImage = getImageBySrc(allImgSrcObj.stepNull)
    } else if (g.step === 2) {
      stepImage = getImageBySrc(allImgSrcObj.stepFull)
    }
    context.drawImage(stepImage, 920, 580)

  }


  drawPlants() {
    let plants = window.main.plants
    plants.forEach(plant => {
      plant.update();
      plant.draw(context);
      // console.log(plant.sunTimer)

      if (plant.canShoot) {
        plant.bullet.forEach(bullet => {
          bullet.update(); // 更新子弹位置
          bullet.draw(context); // 绘制子弹
        });
      }
    });

  }

  drawWin() {
    let img = getImageBySrc(allImgSrcObj.win)
    context.drawImage(img, 600, 400, 166, 134)
  }

  drawZombies() {
    let zombies = window.main.zombies
    // console.log(zombies)
    for (let zombie of zombies) {
      zombie.update()
      zombie.draw(context)
      if (zombie.x < 50) {
        this.state = this.state_ZOMBIEWON
      }
    }
  }

  drawZombiesWin() {
    let img = getImageBySrc(allImgSrcObj.zombieswin)
    context.drawImage(img, 300, 100, 564, 468)
  }

  //能否放置植物方法
  iscanlayup() {
    let g = this
    for (let plant of window.main.plants) {
      if (plant.row === g.mouseRow && plant.col === g.mouseCol) {
        return false
      }
    }
    return true
  }

  drawShovel() {
    let g = this
    //如果铲子对象存在
    if (g.shovel) {
      g.shovel.x = g.mouseMovex - 8
      g.shovel.y = g.mouseMovey + 20
      g.shovel.draw(context)

    }
  }


  drawPic() {
    let g = this
    if (g.card) {
      let img = getImageBySrc(allImgSrcObj.plants[g.card.name].pic)
      let w;
      let h;
      let x;
      let y;
      if (g.card.name === 'peashooter') {
        w = 71;
        h = 71;
      } else if (g.card.name === 'chomper') {
        w = 130;
        h = 114;
      } else if (g.card.name === 'wallnut') {
        w = 65;
        h = 73;
      } else if (g.card.name === 'cherrybomb') {
        w = 112;
        h = 81;
      } else if (g.card.name === 'sunflower') {
        w = 73;
        h = 74;
      }
      if (g.card.name === 'chomper') {
        x = g.mouseMovex - 10
        y = g.mouseMovey - 30
      } else if (g.card.name === 'cherrybomb') {
        x = g.mouseMovex - 10
        y = g.mouseMovey
      } else {
        x = g.mouseMovex
        y = g.mouseMovey
      }
      // 保存当前画布状态
      context.save();
      // 设置透明度为 70%
      context.globalAlpha = 0.7;
      // 绘制图像
      context.drawImage(img, x, y, w, h)
      // 恢复画布状态
      context.restore();
      // console.log(img)
    }

  }

  // 点击事件
  clickCanvas() {
    let g = this;
    let main = window.main;

    // 监听画布点击事件
    canvas.addEventListener('click', (event) => {
      const rect = canvas.getBoundingClientRect();
      g.mouseX = event.clientX - rect.left;
      g.mouseY = event.clientY - rect.top;
      console.log(g.mouseX, g.mouseY)

      if (!g.shovel) {
        // 处理植物卡片的点击
        if ((g.mouseX >= 72 && g.mouseX <= 115) && (g.mouseY >= 8 && g.mouseY <= 66)) {
          if (!g.clickcardg) {
            g.card = main.cards[0];
            handleCardSelection();
          }
        } else if ((g.mouseX >= 124 && g.mouseX <= 169) && (g.mouseY >= 8 && g.mouseY <= 66)) {
          if (!g.clickcardg) {
            g.card = main.cards[1];
            handleCardSelection();
          }
        } else if ((g.mouseX >= 179 && g.mouseX <= 222) && (g.mouseY >= 8 && g.mouseY <= 66)) {
          if (!g.clickcardg) {
            g.card = main.cards[2];
            handleCardSelection();
          }
        } else if ((g.mouseX >= 232 && g.mouseX <= 275) && (g.mouseY >= 8 && g.mouseY <= 66)) {
          if (!g.clickcardg) {
            g.card = main.cards[3];
            handleCardSelection();
          }
        } else if ((g.mouseX >= 283 && g.mouseX <= 328) && (g.mouseY >= 8 && g.mouseY <= 66)) {
          if (!g.clickcardg) {
            g.card = main.cards[4];
            handleCardSelection();
          }

        } else if ((g.mouseX >= 900 && g.mouseX <= 1000) && (g.mouseY >= 0 && g.mouseY <= 50)) {
          gamejframe.style.display = 'none'
          menu.style.display = 'block'
          main.reset()
        }
      }
      if ((g.mouseX >= 1005 && g.mouseX <= 1080) && (g.mouseY >= 7 && g.mouseY <= 40)) {
        g.shovel = Shovel.new();
      }
      if ((g.mouseX >= 175 && g.mouseX <= 925) && (g.mouseY >= 85 && g.mouseY <= 584)) {
        g.mouseCol = parseInt((g.mouseX - 90) / (907 - 175) * 9);
        g.mouseRow = parseInt(g.mouseY / (569 - 78) * 5);
        console.log(g.mouseCol, g.mouseRow)
        if (g.clickcardg) {
          if (g.iscanlayup() && g.card && g.mouseCol >= 1 && g.mouseRow >= 1 && g.mouseRow <= 5 && g.mouseCol <= 9) {
            let info = {
              section: g.card.name,
              col: g.mouseCol,
              row: g.mouseRow,
              x: main.plant_info.x,
              y: main.plant_info.y + 100 * (g.mouseRow - 1),
            };

            // Adjust position based on column
            info.x += [20, 101, 185, 273, 354, 440, 526, 604, 690][info.col - 1];

            if (info.section === 'chomper') {
              info.x -= 5;
              info.y -= 50;
            }
            if (info.section === 'cherrybomb') {
              info.x -= 10;
            }

            main.plants.push(Plant.new(info));
            main.allSun -= g.card.sun_val;
            g.card.isspacing = true
            g.card.timer_num = g.card.timer_spacing / 1000
            g.card.startCooldown()
            g.clickcardg = false;
            g.card = null;
          }
        } else if (g.shovel) {
          g.mouseCol = parseInt((g.mouseX - 90) / (907 - 175) * 9);
          g.mouseRow = parseInt(g.mouseY / (569 - 78) * 5);
          for (let plant of main.plants) {
            if (plant.row === g.mouseRow && plant.col === g.mouseCol) {
              plant.life = -1
              g.shovel = null
            }
          }
        }
      }
    });

    // 监听右键点击事件
    document.addEventListener('contextmenu', (event) => {
      if (g.card) {
        g.card = null;
        g.clickcardg = false; // 确保取消选中的状态
      } else {
        g.shovel = null;
      }
      event.preventDefault();
    });

    // 处理卡片选择逻辑
    function handleCardSelection() {
      if (main.allSun >= g.card.sun_val && g.card.timer_num === 0 && g.card.canClick) {
        g.clickcardg = true
      } else {
        g.card = null;
      }
    }
  }


  setTimer(main) {
    let g = this
    let now = new Date()
    let delatime = now - g.lastUpdateTime

    if (main.zombieNum >= 10 && g.state === g.state_RUNNING) {
      main.clearZombies()
      if (main.zombies.length === 0) {
        setTimeout(() => {
          g.state = g.state_PLANTWON
          g.step = 2
        }, 1000);
      }
    }

    //清空画布
    context.clearRect(0, 0, canvas.width, canvas.height)
    //绘制太阳框背景
    g.drawsunBg()
    g.drawCards()
    g.drawTextSun()
    g.drawShovelbg()
    g.drawCars()


    if (g.state === g.state_START) {

    }
    else if (g.state === g.state_RUNNING) {
      // g.drawBegin()
      g.drawPlants()
      g.drawZombies()
      g.drawStepImg()
      g.drawPic()
      g.drawShovel()
      g.drawReturn()
      //游戏进行中
    }
    else if (g.state === g.state_PLANTWON) {
      for (let card of main.cards) {
        card.canClick = false
      }
      for (let plant of main.plants) {
        if (plant.section === 'sunflower') {
          plant.clearsunTimer()
        }
      }
      g.drawPlants()
      g.drawStepImg()
      main.clearSunTimer()
      g.drawWin()
      g.drawReturn()

    }
    else if (g.state === g.state_ZOMBIEWON) {
      for (let card of main.cards) {
        card.canClick = false
      }
      for (let plant of main.plants) {
        if (plant.section === 'sunflower') {
          plant.clearsunTimer()
        }
      }
      g.drawPlants()
      g.drawZombiesWin()
      g.drawStepImg()
      g.drawPic()
      g.drawShovel()
      main.clearSunTimer()
      g.drawReturn()
      g.drawStepImg()
    }


  }

  init() {
    let g = this
    // 获取主页面中的变量类
    main = window.main
    window.addEventListener('load', function () {
      g.timer = setInterval(function () {
        g.setTimer(main)
      }, 1000 / g.fps)
    })

    btn.addEventListener('click', () => {
      //点击按钮离开游戏主页面，显示游戏开使页面
      g.state = g.state_START
      startjframe.style.display = 'none'
      menu.style.display = 'block'
      main.reset()
      audio1.autoplay = true
      audio1.play()
      audio1.loop = true

    })
    menu_btn.addEventListener('click', function () {
      g.state = g.state_RUNNING
      menu.style.display = 'none'
      gamejframe.style.display = 'block'
      for (let card of main.cards) {
        card.canClick = true
      }

      main.setTimerZombies()
      main.setSunTimer()
      main.setCars(main.cars_info)
      main.setCards(main.cards_info)


      audio1.pause()
      audio2.play()
      audio2.autoplay = true
      audio2.loop = true

      // 确保 point 已经加载完毕
      point.autoplay = true;
      point.play().catch(error => {
        console.error('Error playing point audio:', error);
      });

    })
    // 注册鼠标移动事件
    canvas.onmousemove = function (event) {
      let rect = canvas.getBoundingClientRect();
      g.mouseMovex = (event.clientX - rect.left) - 28;
      g.mouseMovey = (event.clientY - rect.top) - 39;

    }
    this.clickCanvas()
  }

}

